package com.e_manager.soft.emanager.rabbitMQ;


import com.alibaba.fastjson.JSON;
import com.e_manager.soft.emanager.entity.Equipment;
import com.e_manager.soft.emanager.entity.MstMessage;
import com.e_manager.soft.emanager.entity.User;
import com.e_manager.soft.emanager.service.MstMessageService;
import com.e_manager.soft.emanager.util.DateUtil;
import com.e_manager.soft.emanager.util.XingeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/18 0018.
 */
public class AgreementRabbitMQ implements MessageListener {
    @Value("${ANDROID_SUPPLY_ACCESS_ID}")
    private Long accessId;

    @Value("${ANDROID_SUPPLY_SECRET_KEY}")
    private String secretKey;

    @Value("${ANDROID_DEVICE}")
    private String android;

    @Value("${IOS_DEVICE}")
    private String ios;

    private static final Logger logger = LoggerFactory.getLogger(AgreementRabbitMQ.class);
    /*@Autowired
    private ITerminalLoraInfoService terminalLoraInfoService;*/
    //private final static String QUEUE_NAME = "queueTest";
    @Autowired
    private MstMessageService mstMessageService;


    @Override
    @SuppressWarnings("unchecked")
    public void onMessage(Message msg) {
        try {
            String body = new String(msg.getBody(), "UTF-8");
            logger.info("BODY DATA:" + body);

            //json转换成map
            Map bodyMap = (Map) JSON.parse(body);

            //获取标志位，flag=1时处理，否则不处理
            if (Integer.parseInt(bodyMap.get("flag").toString())==1) {
                //解析data数据
                Map resultMap = com.e_manager.soft.emanager.util.DataTransformationUtil.dataToMap((String) bodyMap.get("data"));
                //调用多线程，推送并保存数据
                new Thread(new Runnable() {
                    public void run() {
                        // 往数据库保存数据方法
                        MstMessage mstMessage = new MstMessage();
                        mstMessage.setEquipmentCode(String.valueOf(bodyMap.get("id"))); //设备编号
                        mstMessage.setOriginalMessage(String.valueOf(bodyMap.get("data"))); // 原始报文
                        mstMessage.setMessageType(String.valueOf(resultMap.get("messageType"))); //报文类型
                        mstMessage.setWarnType(String.valueOf(resultMap.get("warnType"))); //报警类型
                        mstMessage.setTemperature(String.valueOf(resultMap.get("temperature"))); //温度
                        mstMessage.setHumidity(String.valueOf(resultMap.get("humidity"))); //湿度
                        mstMessage.setVoltage(String.valueOf(resultMap.get("voltage"))); //电压
                        mstMessage.setRunDay(String.valueOf(resultMap.get("day"))); //运行天数
                        //设置报文时间，String需要转换成timestamp
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                        Date date = null;
                        try {
                            date = dateFormat.parse((String) bodyMap.get("time"));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        mstMessage.setMessageDate(DateUtil.dateToString(date)); //报文时间
                        //设置创建人和创建时间
                        mstMessage.setCreateUser("system");
                        mstMessage.setCreateDate(new Timestamp(System.currentTimeMillis()));

                        mstMessageService.insertMstMessage(mstMessage);
                    }
                }).start();
                //调用多线程，推送数据到信鸽平台
                new Thread(new Runnable() {
                    public void run() {
                        //初始化对象
                        Equipment equipment = new Equipment();
                        //取设备编码
                        equipment.setEquipmentCode((String) bodyMap.get("id"));
                        //根据设备取信鸽token
                        List<User> xinToken = mstMessageService.queryXinToken(equipment);
                        if (xinToken!=null && xinToken.size() > 0) {
                            //循环推送
                            for (int i = 0; i < xinToken.size(); i++) {
                                if (xinToken.get(i).getXinToken() != null && !"".equals(xinToken.get(i).getXinToken())) {
                                    resultMap.put("equipmentName", xinToken.get(i).getEquipmentName());
                                    resultMap.put("equipmentCode", bodyMap.get("id"));
                                    if (resultMap.get("messageType").equals("0")) {
                                        String dev = "android";
                                        if (android.equals(xinToken.get(i).getXinDev())) {
                                            dev = android;
                                        }else{
                                            dev = ios;
                                        }
                                        XingeUtils.pushTokenAndroid(accessId, secretKey, "Data", JSON.toJSONString(resultMap), String.valueOf(xinToken.get(i).getXinToken()), 0,dev);
                                    } else {
                                         String devWarning = "";
                                        if (android.equals(xinToken.get(i).getXinDev())) {
                                            devWarning = android;
                                        }else {
                                            devWarning = ios;
                                        }
                                        XingeUtils.pushTokenAndroid(accessId, secretKey, "E温馨提示：屋内环境出现异常请您及时查看！", JSON.toJSONString(resultMap), String.valueOf(xinToken.get(i).getXinToken()), 1,devWarning);
                                        XingeUtils.pushTokenAndroid(accessId, secretKey, "Data", JSON.toJSONString(resultMap), String.valueOf(xinToken.get(i).getXinToken()), 0,devWarning);
                                    }

                                }
                            }
                        }

                    }
                }).start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
